//
//  AddCardViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/10/8.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import SwiftyJSON

class AddCardViewController: KMViewController {
    
    var addBlock : (()->())?
    
    fileprivate let addBankView = AddBankView()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = addBankCard
        
        let licenseFile = Bundle.main.path(forResource: "aip", ofType: "license")
        let licenseFileData = NSData.init(contentsOfFile: licenseFile!)
        AipOcrService.shard().auth(withLicenseFileData: licenseFileData! as Data)
        
        addSubView()
    }
    
    //MARK: 添加子视图
    fileprivate func addSubView() {
        
        addBankView.delegate = self
        self.view.addSubview(addBankView)
        
        addBankView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    

}

extension AddCardViewController : AddBankViewDelegate {
    
    //MARK: 选择操作
    func selectType(index: Int) {
        
        switch index {
        case 1: //选择银行
            let dataArray = [BankofChina,Constructionbank,ICBC,ABC,CITICBank,BankofCommunications,GuangfaBank,EverbrightBank,HSBCBank,MinshengBank,PufaBank,PostalBank,ChinaMerchantsBank,IndustrialBank,HenanRuralCredit,HSBC,BankofEastAsia,HuishangBank,ShanghaiRuralCommercialBank,GuangzhouBank,BankofBeijing,CitiBank,BaoshangBank,HangzhouBank,ShanghaiBank]
            let selectTypeVC = SelectTypeViewController.init(dataArray: dataArray, selectText: addBankView.bankText)
            selectTypeVC.modalPresentationStyle = .overCurrentContext
            selectTypeVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            selectTypeVC.textBlock = { (text) in
                self.addBankView.bankText = text
            }
            self.present(selectTypeVC, animated: false, completion: nil)
        case 2: //选择卡类型
            
            let dataArray = [creditCard_title,debitCard]
            let selectTypeVC = SelectTypeViewController.init(dataArray: dataArray, selectText: addBankView.cardText)
            selectTypeVC.modalPresentationStyle = .overCurrentContext
            selectTypeVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            selectTypeVC.textBlock = { (text) in
                self.addBankView.cardText = text
            }
            self.present(selectTypeVC, animated: false, completion: nil)
        case 3: //添加银行卡
            addBabkCard()
        case 4: //识别银行
            bankIdentification()
        default:
            break
        }
    }
    
    //MARK: 添加银行卡
    fileprivate func addBabkCard() {
        
        if self.addBankView.numberField.text == "" {
            KMTool.showText(_text: inputBankCardNumber)
            return
        }
        
        if self.addBankView.nameField.text == "" {
            KMTool.showText(_text: inputName)
            return
        }
        
        KMTool.requestMethod(.post, URLString: url_addBankCard, parameters: ["user_name":KMTool.stringForEnumKey(.phone) ?? "","bank":self.addBankView.bankText,"card":self.addBankView.numberField.text!,"card_type":self.addBankView.cardText,"user":self.addBankView.nameField.text!], success: { (value, json) in
            
            if json["status"].stringValue == "0" {
                
                self.addBlock!()
                self.navigationController?.popViewController(animated: true)
            }
            
            KMTool.showText(_text: json["data"].stringValue)
            
            
        }) {
            
            KMTool.showText(_text: failToAdd)
        }
    }
    
    //MARK: 识别银行卡
    fileprivate func bankIdentification() {
        
        let vc = AipCaptureCardVC.viewController(with: .bankCard) { (image) in
            //成功扫描身份证
            AipOcrService.shard().detectBankCard(from: image, successHandler: { (result) in
                
                let dic = JSON.init(result!)
                MyLog(dic)
                let bankCardNumber = dic["result"]["bank_card_number"].stringValue
                let bankType = dic["result"]["bank_name"].stringValue
                let cardType = dic["result"]["bank_card_type"].stringValue
                
                //主线程刷新UI
                DispatchQueue.main.async(execute: {
                    
                    self.addBankView.numberField.text = bankCardNumber
                    self.addBankView.bankText = bankType
                    if cardType == "1" {
                        self.addBankView.cardText = debitCard
                    }else if cardType == "2" {
                        self.addBankView.cardText = creditCard
                    }
                    
                    self.dismiss(animated: true, completion: nil)
                })
                
            }, failHandler: { (error) in
                MyLog(error.debugDescription)
                
                //主线程刷新UI
                DispatchQueue.main.async(execute: {
                    KMTool.showText(_text: failToRecognized)
                    self.dismiss(animated: true, completion: nil)
                })
            })
        }
        
        self.present(vc!, animated: true, completion: nil)
    }
    
}
